package com.example.kotlincoroutines.kotlin

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 *  GlobalScope 生命周期依赖整个应用程序，即使界面销毁了，协程依然在运行
 */
fun main() {
    //官方不建议使用
    //单例进行启动
//    val globalScope = GlobalScope
//    globalScope.launch {
////        delay(1000)
//        println("hello")
//    }
//    globalScope.launch {
////        delay(1000)
//        println("world")
//    }
//    Exception in thread "main" java.lang.IllegalStateException: Scope cannot be cancelled because it does not have a job: kotlinx.coroutines.GlobalScope@6dc1dc69
//    at kotlinx.coroutines.CoroutineScopeKt.cancel(CoroutineScope.kt:286)
//    at kotlinx.coroutines.CoroutineScopeKt.cancel$default(CoroutineScope.kt:285)
//    at com.example.kotlincoroutines.kotlin.GlobalScope03Kt.main(GlobalScope03.kt:27)
//    at com.example.kotlincoroutines.kotlin.GlobalScope03Kt.main(GlobalScope03.kt)
//    globalScope.cancel() //不能取消
//    while (true);

    val coroutineScope = CoroutineScope(Dispatchers.Default)
    coroutineScope.launch {
//        delay(3000)
        println("start")
    }
    coroutineScope.launch {
//        delay(3000)
        println("end")
    }
    coroutineScope.cancel()
    while (true);

}